package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        String username = req.getParameter("username");
        String password1 = req.getParameter("password1");
        String password2 = req.getParameter("password2");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String checkbox = req.getParameter("checkbox");

        if(username.equals("") || password1.equals("") || password2.equals("") || email.equals("") || phone.equals("")){
            String html = "输入框的参数缺少，请确保输入框中都有参数输入！";
            resp.getWriter().write(html);
            return;
        }

        if(checkbox == null){
            String html = "请知晓用户协议，勾选同意协议注册按键！";
            resp.getWriter().write(html);
            return;
        }

        UserDao userDao = new UserDao();
        User user = userDao.selectByUsername(username);

        if(user != null){
            String html = "该用户名已存在，请重新输入用户名！";
            resp.getWriter().write(html);
            return;
        }

        if(!password1.equals(password2)){
            String html = "先后两次输入的用户密码不相同，请重新输入！";
            resp.getWriter().write(html);
            return;
        }

        User NewUser = new User();
        NewUser.setUsername(username);
        NewUser.setPassword(password1);
        NewUser.setEmail(email);
        NewUser.setPhone(phone);
        userDao.addUser(NewUser);

        resp.sendRedirect("blog_login.html");

    }
}
